﻿namespace Stopwatch
{
    using Stopwatch.Core;
    using Stopwatch.Core.Persistence;

    public sealed class Context : System.IDisposable
    {
        static Context context;

        private Context()
        {
        }

        public IWatch Watch { get; private set; }

        public ITimer Timer { get; private set; }

        public void Save()
        {
            StorageFactory.Storage.Write(this.Timer);
            StorageFactory.Storage.Write(this.Watch);
        }

        /// <summary>
        /// release the resources
        /// </summary>
        public static void Release()
        {
            context.Dispose();
            context = null;
        }

        public static Context Load()
        {
            if (context == null)
            {
                context = new Context();

                context.Timer = StorageFactory.Storage.Read<StopTimer>();
                if (context.Timer == null)
                {
                    context.Timer = new StopTimer();
                }

                context.Watch = StorageFactory.Storage.Read<StopWatch>();
                if (context.Watch == null)
                {
                    context.Watch = new StopWatch();
                }
            }

            return context;
        }

        public void Dispose()
        {
            StorageFactory.Storage.Delete<StopTimer>();
            StorageFactory.Storage.Delete<StopWatch>();
        }
    }
}
